package com.xfc.quartz.task;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xfc.message.NoticeMessage;
import com.xfc.school.domain.ScAuditionClassInfo;
import com.xfc.school.domain.ScCourse;
import com.xfc.school.domain.ScTeacher;
import com.xfc.school.service.IScAuditionClassInfoService;
import com.xfc.school.service.IScCourseService;
import com.xfc.school.service.IScTeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 试听课提醒
 * @author lcj
 */
@Slf4j
@Component("AuditionCourseTask")
public class AuditionCourseTask {

    /**学校地址*/
    @Value("${wx.courseUrl}")
    private String courseUrl;

    @Autowired
    private NoticeMessage message;

    @Autowired
    private IScCourseService courseService;

    @Autowired
    private IScAuditionClassInfoService scAuditionClassInfoService;

    @Autowired
    private IScTeacherService teacherService;

    public void courseMessage(){
        log.info("试听课提醒开始:{}", DateUtil.now());
        Date newDate = DateUtil.offset( DateUtil.date(), DateField.DAY_OF_MONTH, 1);
        //查询所有试听课
        QueryWrapper<ScCourse> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("type",1);
        queryWrapper.eq("state",0);
        List<ScCourse> scCourseList=courseService.list(queryWrapper);
        scCourseList.forEach(l->{
            //查询试听课预约
            QueryWrapper<ScAuditionClassInfo> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.apply(Objects.nonNull(newDate),
                    "date_format (start_time,'%Y-%m-%d') = date_format('" +  DateUtil.format(newDate, "yyyy-MM-dd") + "','%Y-%m-%d')");
            queryWrapper1.eq("status",1);
            List<ScAuditionClassInfo> scAuditionClassInfoList=scAuditionClassInfoService.list(queryWrapper1);
            scAuditionClassInfoList.forEach(a->{
                //查询老师名称
                ScTeacher teacher=teacherService.getById(a.getTeacherNo());
                //发起通知
                message.courseMessage(a.getApplicantOpenid(),a.getCourseName(),courseUrl,Objects.isNull(teacher.getTeacherName())?"":teacher.getTeacherName(),DateUtil.format(a.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
            });
        });
        log.info("试听课提醒结束:{}", DateUtil.now());
    }
}
